package com.shuyuntu.proposal.security;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * 对所有设计权限管理方法的拦截器,作用于Controller类的方法之上
 * Created by limeng on 16/8/15.
 */
public class SecurityCheckInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Method method = invocation.getMethod();
        // 被拦截方法,声明的参数里总有一个是Session的子类,否则权限检查无法进行
        Object[] args = invocation.getArguments();
        HttpSession session = null;
        for (Object arg : args) {
            if (arg instanceof HttpSession) {
                session = (HttpSession) arg;
            }
        }
        UseSecurity annotation = method.getAnnotation(UseSecurity.class);
        securityHolder.permissionCheck(session, annotation);

        return invocation.proceed();
    }

    @Autowired
    private SecurityHolder securityHolder;

    public SecurityHolder getSecurityHolder() {
        return securityHolder;
    }

    public void setSecurityHolder(SecurityHolder securityHolder) {
        this.securityHolder = securityHolder;
    }
}
